﻿//扩展jquery：方便处理url参数
(function($) {
    $.query = function(key, value, url) {
        if (!url) {
            url = window.location.href;
        }

        //set
        if (value !== undefined) {
            var keyValue = value === null ? '' : key + "=" + encodeURIComponent(value);
            var reg = new RegExp("([\?&])" + key + "=([^&#]*)", "gi");
            if (url.match(reg)) {
                url = url.replace(reg, "$1" + keyValue);
                if (!keyValue) {
                    url = url.replace(new RegExp("([\?&])&"), "$1");
                    url = url.replace(new RegExp("[\?&](#|$)"), "$1");
                }
            } else if (keyValue) {
                keyValue = (url.indexOf("?") > 0 ? (url.match(new RegExp("[\?](#|$)")) ? "" : "&") : "?") + keyValue;
                if (url.indexOf("#") > 0) {
                    url = url.replace('#', keyValue + "#");
                } else {
                    url += keyValue;
                }
            }
            return url;
        }

        //get
        var result = url.match(new RegExp("[\?&]" + key + "=([^&#]*)", "i"));
        return result ? decodeURIComponent(result[1]) : null;
    }
})(jQuery);

//收藏夹
function AddFavorite(siteName) {
    var host = window.location.host;
    if (host != "") {
        try {
            window.external.addFavorite("http://" + host + "/", siteName);
        }
        catch (e) {
            try {
                window.sidebar.addPanel(siteName, "http://" + host + "/", "");
            }
            catch (e) {
                alert(lang.add_favorite);
            }
        } 
    }
}

//主页
function SetHomePage() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        var host = window.location.host;
        if (host != "") {
            document.body.setHomePage("http://" + host + "/");
        }
    } else {
        alert(lang.set_homepage);
    }
}

//搜索
function GoSearch(url, inputId, isNewWindow) {
    var keywords = $('#' + inputId).val();
    if (keywords != lang.input_search) {
        if (isNewWindow) {
            window.open($.query('k', keywords, url), "_blank");
        } else {
            window.location.href = $.query('k', keywords, url);
        }
    } else {
        alert(lang.tips_search);
    }
}

// 清除input默认值
function Cls(el, message, isSetColor) {
    var obj;
    if (typeof (el) == "string") {
        obj = document.getElementById(id);
    } else {
        obj = el;
    }
    if (obj.value == message) {
        obj.value = "";
        if (isSetColor) {
            obj.style.color = "#000";
        }
    }
    obj.onblur = function () {
        if (obj.value == "") {
            obj.value = message;
            if (isSetColor) {
                obj.style.color = "#999";
            }
        }
    }
}

//UL左卷动
function ScrollLeft(id) {
    var frameObj = document.getElementById(id);
    if (frameObj) {
        var speed = 30;
        var step = 1;
        var UL = frameObj.getElementsByTagName("ul")[0];
        var liItems = UL.getElementsByTagName("li");
        var contentWidth = 0;
        for (var i = 0; i < liItems.length; i++) {
            contentWidth += liItems[i].scrollWidth;
        }
        UL.innerHTML += UL.innerHTML;
        function ScrollRun() {
            if (frameObj.scrollLeft >= contentWidth) {
                frameObj.scrollLeft = 0;
            }
            else {
                frameObj.scrollLeft += step;
            }
        }
        var ScrollTimer = setInterval(ScrollRun, speed);
        frameObj.onmouseover = function () { clearInterval(ScrollTimer); };
        frameObj.onmouseout = function () { ScrollTimer = setInterval(ScrollRun, speed); };
    }
}

//更换验证码
function VerifyCodeRefresh(target) {
    var img;
    if (typeof (target) == "string") {
        img = document.getElementById(target);
    } else {
        img = target;
    }
    var rd = Math.random();
    img.src = $.query('r', Math.random(), img.src);
}

//闹铃：参数（响铃间隔，响铃次数，响铃动作）
function Ticker(interval, count, action) {
    if (action) {
        action(count);
        count--;
        var sysTimer = setInterval(function () {
            if (count >= 0) {
                action(count);
                count--;
            } else {
                clearInterval(sysTimer);
            }
        }, interval);
    }
}

//在线客服窗口效果初始化
$(document).ready(function () {
    $("#kf_wrap").on('mouseover','#kf_sidebar',function(){
        $(this).hide();
        $("#kf_main").show();
    }).on('mouseleave','#kf_main',function(){
    	$(this).hide();
        $("#kf_sidebar").show();
    });
    $(window).scroll(function () {
        var windowScrollTop = $(window).scrollTop();
        $("#kf_wrap").animate({ top: windowScrollTop + 200 }, 0);
    });
});

//图片自适应
function ImageShow(wrap, src) {
    wrap.css("display", "block");
    wrap.css("position", "relative");
    var img = new Image();
    img.onload = function () {
        var wrap_width = wrap.width();
        var wrap_height = wrap.height();
        if (wrap_width == 0) {
            wrap.width(100);
            wrap_width = 100;
        }
        if (wrap_height == 0) {
            wrap.height(100);
            wrap_height = 100;
        }
        if ((wrap_width * img.height) > (wrap_height * img.width)) {
            if (wrap_height < img.height) {
                img.width = parseInt((img.width * wrap_height) / img.height);
                img.height = wrap_height;
            }
        } else {
            if (wrap_width < img.width) {
                img.height = parseInt((img.height * wrap_width) / img.width);
                img.width = wrap_width;
            }
        }
        $(img).css("position", "absolute");
        $(img).css("left", parseInt((wrap_width - img.width) / 2) + parseInt(wrap.css("padding-left")) + "px");
        $(img).css("top", parseInt((wrap_height - img.height) / 2) + parseInt(wrap.css("padding-top")) + "px");
        wrap.append(img);
    };
    img.src = src;
}
$(document).ready(function () {
    $("div[src],a[src]").each(function () {
        ImageShow($(this), $(this).attr("src"));
    });
});

//会员bar
function check_member(){
    $.getJSON(url_member_check, {}, function(rs) {
        var html = '<a class="member_login" target="_blank">'+lang.bar_login+'</a>\r\n<a class="member_register" target="_blank">'+lang.bar_regist+'</a>';
        if (rs.err === 0) {
            html = '<a class="member_index" target="_blank">' + rs.data.username + '</a>\r\n<a class="member_logout">'+lang.bar_logout+'</a>';            
        }
        $("#member_bar").html(html);
    });    
}
$(document).ready(function () {
    $("#member_bar").on('click', function(e){
        var link = $(e.target);
        switch(link.attr('class'))
        {
            case 'member_login':
                link.attr('href',url_member_login);
                return true;
            case 'member_register':
                link.attr('href',url_member_register);
                return true;
            case 'member_index':
                link.attr('href',url_member_index);
                return true;
            case 'member_logout':
                $.getJSON(url_member_logout, {}, function(rs){
                    if(rs.err === 0){
                        check_member();            
                    }else{
                        alert(rs.msg);
                    }
                });
                return false;
        }
    });
    check_member();
});

//切换语言
function switch_language() {
	var languages = [ 'zh_cn', 'en' ];
	var url = window.location.href.split( '/' );
	var i = 3;
	if( window.location.href.indexOf( '/index.php' ) > 0 ){
		i++;
	}
	for ( var j = 0, n = languages.length; j < n; j++ ) {
		if( url[i] === languages[j] ){
			var next = j+1<n?j+1:0;
			if( languages[next] === 'zh_cn' ){
				url.splice( i, 1 );
			}else{
				url[i] = languages[next];
			}
			window.location.href = url.join( '/' );
			return;
		}
	}
	url.splice( i, 0, languages[1] );
	window.location.href = url.join( '/' );
}